<?php $gridId=rand(0,10000); ?>
<script type="text/javascript">
Ext.onReady(function(){
Ext.QuickTips.init();
Ext.BLANK_IMAGE_URL = '<?=$this->baseUrl?>/public/images/default/s.gif';

var User = Ext.data.Record.create([
           // 下面的 "name" 匹配读到的标签名称, 除了 "birthDay",它被映射到标签 "birth"
           {name: 'u_id', type: 'int'},
           {name: 'username', type: 'string'},
		   {name: 'realname', type: 'string'},
           {name: 'email', type: 'string'},
		   {name: 'input_date', type: 'string'},
           {name: 'role', type: 'string'},
		   {name:'pwd',type:'string'}
      ]);

var member_store_combo=new Ext.form.ComboBox({
										 fieldLabel:'role',
										 store:new Ext.data.JsonStore({
																	  autoLoad:true,
																	  url:'<?=$this->baseUrl?>/admin/roledata',
																	  root:'results',
																	  fields:['role_name']
																	  }),										
        								displayField:'role_name',
        								valueField :'role_name',
										hiddenName:"role",
        								typeAhead:true,
        								mode:'local',
        								triggerAction:'all',
        								emptyText:'请选择...',
        								selectOnFocus:true
										 });



var ds=new Ext.data.Store({
							  proxy:new Ext.data.HttpProxy({
									url:'<?=$this->baseUrl?>/admin/userdata/'
									}),
							  reader:new Ext.data.JsonReader({
									root:'results',
									totalProperty:'total',
									id:'u_id'
									},User)
	});		 
//定义列模型
var cm=new Ext.grid.ColumnModel([	
							new Ext.grid.RowNumberer(),									 
							{header:'登录名',dataIndex:'username',width:200,editor:new Ext.form.TextField({allowBlank:false,vtype:'alphanum'})},
							{header:'实名',dataIndex:'realname',width:150,editor:new Ext.form.TextField({allowBlank:false})},
							{header:'邮箱',dataIndex:'email',width:150,editor:new Ext.form.TextField({allowBlank:false,vtype:'email'})},
							{header:'加入日期',dataIndex:'input_date',width:250},
							{header:'权限组',dataIndex:'role',width:250,editor:member_store_combo}
	]);
cm.defaultSortable = true; 


//每页显示记录数
var mypagedata=[
				['10','10'],
				 ['15','15'],
				 ['20','20'],
				 ['40','40'],
				 ['200','200']
				 ];	
var page_size_store=new Ext.data.SimpleStore({
									   fields:[
											   {name:'id'},
											   {name:'name'},
									   		  ]
									   });
page_size_store.loadData(mypagedata);
var pagesize_combo=new Ext.form.ComboBox({
										 store:page_size_store,
										 width:50,										
										 emptyText:'10',
										 mode:'local',
										 triggerAction:'all',
										 valueField:'name',
										 displayField:'id'
										 });
pagesize_combo.on('select',function(e){										
										var pagesize=parseInt(e.getValue());
										pagBar.pageSize=pagesize;
										ds.load({params:{start:0,limit:pagesize}});
										//grid.render();
										});	

//定义分页条栏				 
var pagBar=new Ext.PagingToolbar({
										pageSize:30,
										store:ds,
										displayInfo:true,
										displayMsg:'第{0}到{1}条记录 共{2}条记录',
										emptyMsg:'没有数据记录',
										//plugins: filters,
										items:['-','每页显示',pagesize_combo,'条记录','-']
									 });
//定义工具栏								 
var tb=new Ext.Toolbar({
							items:[
								   		 {
											text:'增加',
											iconCls:'icn-add',
											handler:menuAdd
											},{
											text:'删除',
											iconCls:'icn-delete',
											handler:menuDel
											},{
											id:'menu_save',
											text:'保存',	
											iconCls:'icn-edit',
											hidden:true,
											handler:menuSave
											},{
											xtype:'tbfill'
											},{
											text:'快速添加',
											iconCls:'icn-add',
											handler:menuAddQuick
										}
											 
								 ]
	});									
//定义容器
var grid=new Ext.grid.EditorGridPanel({
									renderTo:'grid_<?=$gridId?>',
									store:ds,
									cm:cm,									
									height:500,
									minHeight:300,
									//autoHeight:true,
									autoWidht:true,								
									//plugins: filters,
									loadMask:{msg:'加载服务端数据中',store:ds},	
									autoScroll:true,
									stripeRows:true,									
        							animCollapse: false,
									//sm:new Ext.grid.CheckboxSelectionModel({singleSelect:false}),
									monitorWindowResize: true,	
									title:'用户列表',
									clicksToEdit:true,
									sm:new Ext.grid.CheckboxSelectionModel({singleSelect:false}),
									tbar:tb,
									bbar:pagBar
									});
//显示数据
ds.load({params:{start:0,limit:30}});
grid.render();

grid.on("afteredit",afterEdit,grid);

function afterEdit(e){
	Ext.getCmp('menu_save').show();	
	}

function afterEditSave(){
	var　modified　=　ds.modified;
	var json=[];
	Ext.each(modified,function(field){
						json.push(field.data);
						});
	//alert(json.length);
	if(json.length>0){
		//console.log(Ext.util.JSON.encode(json));
		Ext.Ajax.request({
						 url		: '<?=$this->baseUrl?>/user/edit',
						 params		: {data:Ext.util.JSON.encode(json)},
						 method		: 'POST',
						 success	: function(response){
							 	Ext.Msg.alert('信息','数据更新成功',function(){																	
										Ext.getCmp('content').getActiveTab().getUpdater().refresh();																
								});
							 }
						 });
		}
	else{
		Ext.Msg.alert("信息","没有修改任何信息");
		}
	//alert(e.field);
	//alert(e.record.get('role'));
}

function menuDel(){												
													var selectRows=grid.getSelectionModel().getSelections();												
												if(selectRows.length==0){
													Ext.MessageBox.alert('提示','请选择一条数据');
													}
												else{		
												//Ext.MessageBox.confirm("确认么","确定要提交么",showResult);	
													var message="";
													for(var i=0;i<selectRows.length;i++){
														if(i!=0){
															message+=",";
															}
														message+=selectRows[i].get('u_id');
														}
													Ext.Ajax.request({
																	 url:'<?=$this->baseUrl?>/user/del',
																	 params:{id:message},																																		 																	success:function(response,option){
																var temp=Ext.util.JSON.decode(response.responseText);																
																ds.load({params:{start:0,limit:30}});
																grid.render();
																		 },
																	failure:function(response,option){
																		var temp=Ext.util.JSON.decode(response.responseText);
																		Ext.MessageBox.alert('waring',temp.msg);
																		}
																	 });
													//Ext.MessageBox.alert('执行','你选择的是第'+message+'条数据');
													}
												}

function menuAdd(){
													if(!win_user_add){
		var form_add=new Ext.FormPanel({								   
		labelAlign:'top',
		frame:true,
		plain:true,
		id:'user_add',
		buttonAlign : 'center',  
		bodyStyle:'padding:5px',
		width:800,
		items:[{
			   layout:'column',
			   border:false,
			   items:[{
			   		columnWidth:.5,
					layout:'form',
					border:false,
					items:[{
						   xtype:'textfield',
						   fieldLabel:'realname',
						   name:'realname',
						   id:'realname',
						   anchor:'80%',
						   allowBlank:false
						   },
						   {
						   xtype:'textfield',
						   fieldLabel:'password',
						   name:'pwd1',
						   inputType : 'password',
						   anchor:'80%',
						   allowBlank:false
						   },
						   {
						   xtype:'textfield',
						   fieldLabel:'Email',
						   name:'email',
						   value:'name@onechoose.com',
						   anchor:'80%',
						   allowBlank:false,
						   vtype:'email'
						   }]
					  },
					  {
			   		columnWidth:.5,
					layout:'form',
					border:false,
					items:[{
						   xtype:'textfield',
						   fieldLabel:'username',
						   name:'username',
						   id:'username',
						   anchor:'80%',
						   allowBlank:false
						   },
						   {
						   xtype:'textfield',
						   fieldLabel:'repeat password',
						   name:'pwd2',
						   inputType : 'password',
						   anchor:'80%'
						   },member_store_combo]
					  }]			   
			   },{
				    xtype:'fieldset',
            		checkboxToggle:true,
            		title: '自定义权限',
            		autoHeight:true,
					width:800,
					height:300,
            		collapsed: true,
					items :[{html:"<iframe id='myiframe' width=800 height=300 frameborder=0 scrolling=auto src='<?=$this->baseUrl?>/admin/controlprivate'></iframe>"
			   } ,{
				   xtype:'textfield',
				   name:'roleprivate',
				   hidden:true,
				   id:'roleprivate',
				   labelSeparator:' '
				   }                 
				   ]
				   }],
		buttons:[{
				 text:'save',
				 name:'submit',
				 id:'save',
				 handler:function(){
					 if(form_add.getForm().isValid()){
					  //提交iframe里的表单
					  if (document.all){//IE
                		doc = document.frames["myiframe"].document;
        			}else{//Firefox   
                	doc = document.getElementById("myiframe").contentDocument;
        			} 
					 doc.getElementById('private_control').submit();					 				
					 var value=doc.getElementById('role').value;
					 Ext.getCmp('roleprivate').setValue(value);
					 form_add.getForm().submit({
							waitTitle: '提示',
							waitMsg:'等待中',
							url:'<?=$this->baseUrl?>/user/add',
							method:'post',
							success:function(form,action){
								var temp=Ext.util.JSON.decode(action.response.responseText);
								//Ext.MessageBox.alert('成功',temp.msg);
								win_user_add.hide();
								ds.load({params:{start:0,limit:30}});
								grid.render();
								},
							failure:function(form,action){
								var temp=Ext.util.JSON.decode(action.response.responseText);
								Ext.MessageBox.alert('waring',temp.msg);
								}
							});
					 }}
				 },
				 {
				text:'cancel',	 
				name:'cancel',
				id:'cancel',
				handler:function(){
					win_user_add.hide();
					}
				}]
	});
												var win_user_add=new Ext.Window({
								 				resizable	: true,
												width		: 800,	
												title		: '用户管理',
												autoHeight	: true,
												items		: [form_add],
												buttonAlign	: 'center',
												listeners	: {"close":function(){
													//alert("关闭");
													//win_user_add.hide();													
													}}
													});	
														}
													win_user_add.show();
													//Ext.getCmp('user_add').show();
													
												}


function menuAddQuick(){
	
	var n = grid.getStore().getCount();// 获得总行数
                var p = new User({
                    u_id:"",
                    username: '',
					realname:'ben',
                    email: 'Ben@onechoose.com',
					input_date:"<?=date('y-m-d h:i:s')?>",
					role:'',
					pwd:'123456'

                });
                grid.stopEditing();// 停止编辑
                ds.insert(n, p);// 插入到最后一行
                grid.startEditing(n, 1);// 开始编辑1单元格
				Ext.getCmp('menu_save').show();
	}
function menuSave(){
	afterEditSave();
	Ext.getCmp('menu_save').hide();
	}
});

</script>
<body style="width:98%;height:100%">
<div id='grid_<?=$gridId?>'></div>
</body>
</html>